﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using PHMEE.Videos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Auditing;

namespace PHMEE.Admin.Videos
{
    /// <summary>
    /// 控制视频播放，停止
    /// </summary>
    [DisableAuditing]
    public class VideoCtlsAppService : PHMEEAdminAppService, IVideoCtlsAppService
    {
        private readonly IConfiguration _configuration;
        private readonly IMqttExtendManager _mqttExtend;
        private readonly IDistributedCache _distributedCache;
        private readonly string Topic;

        public VideoCtlsAppService(IConfiguration configuration, IMqttExtendManager mqttExtend, IDistributedCache distributedCache)
        {
            _configuration = configuration;
            _mqttExtend = mqttExtend;
            _distributedCache = distributedCache;
            Topic = _configuration.GetValue<string>("VidioClient:SendTopic")!;
        }
        /// <summary>
        /// 发送主题并且返回数据
        /// </summary>
        /// <param name="videoAction"></param>
        /// <param name="localchn"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<VideoResControlDto> SetVideoStatus(VideoActionEnum videoAction, int localchn)
        {
            if (localchn < 1 || localchn > 5)
            {
                throw new UserFriendlyException(
                    code: "400",
                    message: $"localchn 参数无效，应在 1 到 5 之间",
                    details: $"输入的 localchn 值为 {localchn}，但它必须是 1 到 5 之间的数字",
                    logLevel: LogLevel.Warning
                );
            }

            //发送播放视频/停止播放/心跳监测主题
            var videoControlDto = new VideoControlDto()
            {
                Type = "control_video",
                ActionId = "1234",
                Action = videoAction.ToString(),
                LocalChn = localchn
            };
            // 设置小写属性命名策略
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                Converters = { new JsonStringEnumConverterLowercase<VideoActionEnum>() }
            };
            string msg = JsonSerializer.Serialize(videoControlDto, options);
            // 发送对应操作视频主题
            await _mqttExtend.SendMessageAsync(Topic, msg);

            // 设置轮询间隔和超时时间
            int maxWaitTime = 30000;
            int interval = 500;
            int elapsedTime = 0;

            while (elapsedTime < maxWaitTime)
            {
                string ResData = await _distributedCache.GetStringAsync(videoAction.ToString());
                if (!string.IsNullOrEmpty(ResData))
                {
                    var result = JsonSerializer.Deserialize<VideoResControlDto>(ResData, options);
                    // 删除 Redis 中的对应 Key
                    //await _distributedCache.RemoveAsync(videoAction.ToString());
                    return result;
                }

                await Task.Delay(interval);
                elapsedTime += interval;
            }
            // 如果超时，抛出异常
            throw new UserFriendlyException(
                code: "500",
                message: $"获取{videoAction}数据失败",
                details: $"在等待 {maxWaitTime / 1000} 秒后，未能获取到{videoAction}数据",
                logLevel: LogLevel.Error
            );
        }

    }
}
